package com.bhs.sansonglogistics.ui.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bhs.sansonglogistics.R;
import com.bhs.sansonglogistics.base.BaseActivity;
import com.bhs.sansonglogistics.base.GlideEngine;
import com.bhs.sansonglogistics.bean.ImageReturn;
import com.bhs.sansonglogistics.bean.PictureBean;
import com.bhs.sansonglogistics.net.NetCallBack;
import com.bhs.sansonglogistics.utils.MyUtils;
import com.bhs.sansonglogistics.utils.ToastUtil;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnExternalPreviewEventListener;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Response;

/**
 * 废弃 等会删除
 */
public class VideoSelectAdapter extends BaseMultiItemQuickAdapter<PictureBean, BaseViewHolder> implements NetCallBack{
        //视频选择的最大数量
        private int maxSelectNum;
        private int index = 0;
        private BaseActivity activity;
        private ArrayList<LocalMedia> localMedia = new ArrayList<>();

        public VideoSelectAdapter(int maxSelectNum, BaseActivity activity) {
            super(new ArrayList<PictureBean>());
            this.maxSelectNum = maxSelectNum;
            this.activity = activity;
            mData.add(new PictureBean(PictureBean.add));
            addItemType(PictureBean.picture, R.layout.item_video);
            addItemType(PictureBean.add, R.layout.item_video_add);
        }



        @Override
        protected void convert(@NonNull BaseViewHolder helper, PictureBean item) {
            if (helper.getItemViewType() == PictureBean.picture) {
                Glide.with(mContext).load(MyUtils.watermark(item.getPath())).into((ImageView) helper.getView(R.id.iv_picture));
                helper.getView(R.id.iv_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        delete(helper.getLayoutPosition());
                    }
                });
                helper.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PictureSelector.create(activity)
                                .openPreview()
                                .setImageEngine(GlideEngine.createGlideEngine())
                                .isAutoVideoPlay(true)
                                .isLoopAutoVideoPlay(true)
                                .setExternalPreviewEventListener(new OnExternalPreviewEventListener() {
                                    @Override
                                    public void onPreviewDelete(int position) {
                                        delete(position);
                                    }

                                    @Override
                                    public boolean onLongPressDownload(Context context, LocalMedia media) {
                                        return false;
                                    }
                                })
                                .startActivityPreview(helper.getLayoutPosition(), true, localMedia);
                    }
                });
            } else {
                helper.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        PictureSelector.create(mContext)
                                .openGallery(SelectMimeType.ofVideo())
                                .setMaxVideoSelectNum(maxSelectNum)
                                .setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                                .setImageEngine(GlideEngine.createGlideEngine())
                                .setSelectedData(localMedia)
                                .forResult(new OnResultCallbackListener<LocalMedia>() {
                                    @SuppressLint("NotifyDataSetChanged")
                                    @Override
                                    public void onResult(ArrayList<LocalMedia> result) {
                                        localMedia = result;
                                        for (LocalMedia localMedia : result) {
                                            boolean isHas = false;
                                            for (PictureBean mDatum : mData) {
                                                if (mDatum.getItemType() == PictureBean.add) {
                                                    mData.remove(mDatum);
                                                }
                                                if (localMedia.getRealPath().equals(mDatum.getPath())) {
                                                    isHas = true;
                                                }
                                            }
                                            if (isHas) {
                                                continue;
                                            }
                                            mData.add(new PictureBean(localMedia.getRealPath()));
                                        }

                                        if (result.size() < maxSelectNum) {
                                            mData.add(new PictureBean(2));
                                        }
                                        notifyDataSetChanged();
                                        activity.loadingPopupShow();
                                        index = 0;
                                        imageUpload();

                                    }

                                    @Override
                                    public void onCancel() {

                                    }
                                });
                    }
                });
            }
        }


        private void imageUpload() {
            if (index >= mData.size()) {
                activity.loadingPopupDismiss();
                return;
            }
            if (mData.get(index).getNetworkPath() == null && mData.get(index).getPath() != null) {
                MultipartBody.Builder builder = new MultipartBody.Builder();
                File file = new File(mData.get(index).getPath());
                RequestBody imageBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                builder.addFormDataPart("file", file.getName(), imageBody);
                builder.addFormDataPart("upload_file", "customer");
                builder.addFormDataPart("type", "app");
                List<MultipartBody.Part> parts = builder.build().parts();
                activity.networkRequest(activity.netApi.imageUpload(parts), this);
            } else {
                index++;
                imageUpload();
            }
        }

        @Override
        public void onResponse(int requestCode, String json, Response<ResponseBody> response) throws Exception {
            ImageReturn dataBean = new Gson().fromJson(json, ImageReturn.class);
            if (dataBean.isStatus()) {
                mData.get(index).setNetworkPath(dataBean.getData().getSrc());
                index++;
                imageUpload();
            } else {
                ToastUtil.show(dataBean.getMsg());
            }
        }

        @Override
        public void onFailure(int requestCode) {

        }

        @SuppressLint("NotifyDataSetChanged")
        public void delete(int position) {
            localMedia.remove(position);
            mData.remove(position);
            if (mData.size() > 0 && mData.get(mData.size() - 1).getItemType() == 1) {
                mData.add(new PictureBean(2));
            }
            if (mData.size() == 0) {
                mData.add(new PictureBean(2));
            }
            notifyDataSetChanged();
        }

        public String getImages() {
            StringBuilder images = new StringBuilder();
            for (PictureBean mDatum : mData) {
                if (mDatum.getItemType() == 1) {
                    images.append(mDatum.getNetworkPath()).append("||");
                }
            }
            if (!TextUtils.isEmpty(images)) {
                images = new StringBuilder(images.substring(0, images.toString().lastIndexOf("||")));
            }
            return images.toString();
        }

        public void setMaxSelectNum(int maxSelectNum) {
            this.maxSelectNum = maxSelectNum;
        }

        public int getMaxSelectNum() {
            return maxSelectNum;
        }


}
